import { message } from "@/Hooks/Element-plus"
import { useUserStore } from "@/stores/modules/user"
import axios from "axios"
import type { Method, AxiosRequestConfig, AxiosResponse } from "axios"
import { error_code } from "./error-code"
import { sendErrorMsg } from "./common"
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
})
// 请求拦截器
service.interceptors.request.use((config) => {
  const userStore = useUserStore()
  if (userStore.token) {
    // 如果有token就携带
    config.headers.token = userStore.token
  }
  return config
})
type Data<T> = {
  code: number
  message: string
  data: T
}
// 必须先拦截一下
// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 这里处理后端返回数据,需要根据实际情况做处理
    if (response.data.code !== 200) {
      // message("error", response.data.message)
      sendErrorMsg({
        code: response.data.code,
        message: response.data.message,
      })
      return
    }
    return response.data
  },
  (err) => {
    sendErrorMsg({
      code: err.response.status,
      message: error_code(err.response.status) || "网络问题",
    })
    return Promise.reject(new Error(err))
  },
)
interface requestParams {
  url: string
  method: Method
  data?: object | string
  config?: AxiosRequestConfig
}
const request = <T>(params: requestParams) => {
  return service.request<T, Data<T>>({
    url: params.url,
    method: params.method || "get",
    [params.method.toLowerCase() === "get" ? "params" : "data"]: params.data,
    ...params.config,
  })
}
export default request
